<?php
namespace My\Controller;

use Utuo\BackgroundController;
use My\Model\DistributionShopOrderModel;
use Utuo\PHPExcel;

class DistributionShopBelongingsController extends BackgroundController {
	
	protected function _initialize() {
		$this->setControllerTitle("财务管理");
		$this->setActionTitle(array(
			'index' => '财务佣金',
		));
		$this->setActionNav("index");
	}	
	
	
	public function indexAction() {
		$type = I('type', 0, 'intval');
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'type' => $type,
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$distributionShopOrderGoodsLists = $this->search( $params, true );
		$this->assign("params", $params);
		$this->assign("distributionShopOrderGoodsLists", $distributionShopOrderGoodsLists);
		$this->display();
	}
	
	/**
	 * 导出Excel
	 */
	public function exportXLSAction() {
		$startDate = I('startDate', 0, 'intval') or $startDate = strtotime('-29 days');
		$endDate = I('endDate', 0, 'intval') or $endDate = time();
		$params = array(
				'startDate' => $startDate,
				'endDate' => $endDate,
		);
		$productOrderGoodsLists = $this->search( $params, false );
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("微美风铃")
					->setLastModifiedBy("微美风铃")
					->setTitle("销售报表")
					->setSubject("销售报表")
					->setDescription("销售报表")
					->setKeywords("销售 报表")
					->setCategory("报表");
	
	
		/*设置标题*/
		$titles = array('ID','订单编号','商品名称','总佣金','实发佣金','成交日期');
		$fields = array('id' => array('type'=>'number'),
				'order_id'=> array('type'=>'string'),
				'product_name'=> array('type'=>'string'),
				'totalBonus' => array('type'=>'number'),
				'infactTotalBonus' => array('type'=>'number'),
				'deal_time'=>array('type'=>'datetime', 'format' => 'Y/m/d h:i:s'));
		$sheet0 = $objPHPExcel->setActiveSheetIndex(0);
		$rowNumber = 1;
		foreach ($titles as $k => $v) {
			$sheet0->setCellValue(chr(ord('A')+$k).$rowNumber, $v);
		}
		$rowNumber++;
		foreach ( $productOrderGoodsLists as $v ) {
			$fieldIndex = 0;
			foreach ( $fields as $k0 => $v0 ) {
				$cellName = chr(ord('A')+$fieldIndex++).$rowNumber;
				$sheet0->setCellValueExplicit($cellName, $this->getShowData($v[$k0], $v0), $this->getCellFormat($v[$k0]));
				//$sheet0->setCellValue($cellName, );
			}
			$rowNumber++;
		}
		$objPHPExcel->getActiveSheet()->setTitle(date('Y年m月d', time($startDate)).'至'.date('Y年m月d', time($endDate))."销售报表");
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="'.date("Ymdhis").'.xls"');
		header('Cache-Control: max-age=0');
		header('Cache-Control: max-age=1'); // IE9时
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
	}
	
	/**
	 * 获得单元格格式
	 * @param unknown $fieldCfg
	 * @return string
	 */
	private function getCellFormat( $fieldCfg ) {
		if( $fieldCfg['type'] == 'string' ) {
			return \PHPExcel_Cell_DataType::TYPE_STRING;
		}elseif( $fieldCfg['type'] == 'money' ) {
			return \PHPExcel_Cell_DataType::TYPE_NUMERIC;
		}
		return \PHPExcel_Cell_DataType::TYPE_STRING;
	}
	
	/**
	 * 获得数据展示格式
	 * @param unknown $value
	 * @param unknown $fieldCfg
	 * @return string|unknown
	 */
	private function getShowData($value, $fieldCfg) {
		if( $fieldCfg['type'] == 'datetime' ) {
			return date( $fieldCfg['format'], $value);
		}
		return $value;
	}
	
	
	/**
	 * 查询
	 * @param unknown $params
	 * @return unknown
	 */
	private function search( $params, $paginate = true ) {
		$page = $this->getPage();
		$condition = array(
				'b.order_status' => DistributionShopOrderModel::ORDER_STATUS_COMPLETED,
				'b.deal_time' => array(array('egt', $params['startDate']), array('elt', $params['endDate']), 'and'),
				'b.cid' => $this->aid,
		);
		$m = M("DistributionShopOrderGoods a")->join("__DISTRIBUTION_SHOP_ORDER__ b on a.order_id=b.id", "LEFT")->where($condition);
		$n = clone $m;
		if( $paginate ) {
			$totalRows = $n->count();
			$m->page($page)->limit($this->getPageSize());
			$this->showPage($totalRows, $this->pageSize);
		}
		$productOrderGoodsLists = $m->field("a.*,b.cid,b.order_id,b.deal_time")->select();
		 
		foreach ( $productOrderGoodsLists as &$v) {
			$baseBonus = array_sum(explode(',', $v['reward_bonus'])); 
			$dealerBonus = array_sum(explode(',', $v['reward_bonus_dealer']));
			$v['totalBonus'] = number_format($v['reward_price']*$v['product_number'] + $v['reward_price_dealer']*$v['product_number'], 2);
			$v['infactTotalBonus'] = number_format($baseBonus + $dealerBonus, 2);
			$v['surplus'] = number_format(($v['product_number']*$v['product_price'] - $v['infactTotalBonus']), 2);
		}
		
		return $productOrderGoodsLists;
	}
		
	
}